<template>
	<div class="padding20">
		<el-row style="margin-bottom: 7px">
			<el-form :inline="true" :model="queryForm" @submit.native.prevent @keyup.enter.native="queryList">
				<el-form-item>
					<fortress-select v-model="queryForm.questionType" :dictList="questionTypeList" placeholder="请选择题目类型" clearable filterable></fortress-select>
				</el-form-item>
				<el-form-item>
					<el-input prefix-icon="el-icon-search" v-model="queryForm.title" autocomplete="off" placeholder="请输入标题" clearable></el-input>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" size="medium" icon="el-icon-search" @click="queryList({ current: 1 })">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="medium" icon="el-icon-refresh-left" @click="resetQueryForm">重置</el-button>
				</el-form-item>
			</el-form>
			<el-button type="primary" size="medium" icon="el-icon-plus" v-if="$tools.hasPermission('study:exam:studyQuestion:save')" @click="handleEdit()">
				添加
			</el-button>
			<el-button v-if="$tools.hasPermission('study:exam:studyQuestion:deleteBatch')" size="medium" type="danger" icon="el-icon-delete" @click="handleDeleteBatch()">
				删除
			</el-button>
			<!-- <el-button size="medium" type="primary" icon="el-icon-upload2" @click="addBatchHandle()">
				导入
			</el-button> -->
			<data-import download-url="https://resource-1251334741.cos.ap-beijing.myqcloud.com/exam_study/%E9%A2%98%E5%BA%93%E6%A8%A1%E6%9D%BF.xls" @upload="onUpload" ref="import"></data-import>
			<div style="float: right; padding-right: 17px">
				<!--				<i class="el-icon-download" style="margin-right: 10px; cursor: pointer" @click="handleExport"></i>-->
				<i class="el-icon-refresh" style="margin-right: 10px; cursor: pointer" @click="refresh"></i>

				<el-popover placement="bottom" width="180" trigger="click" title="列展示" popper-class="columnShows">
					<el-checkbox-group v-model="tableShowList">
						<el-checkbox v-for="item in tableList" :label="item.propName" :key="item.propName" :value="item.propName">
							{{ item.propDesc }}
						</el-checkbox>
					</el-checkbox-group>
					<i slot="reference" class="el-icon-s-operation" style="cursor: pointer"></i>
				</el-popover>
			</div>
		</el-row>
		<el-table ref="multipleTable" :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border>
			<el-table-column type="selection" width="55" show-overflow-tooltip></el-table-column>

			<el-table-column v-if="$tools.isShow('questionType', tableShowList)" prop="questionType" label="题目类型" :show-overflow-tooltip="true" :formatter="questionTypeFmt"></el-table-column>
			<el-table-column v-if="$tools.isShow('title', tableShowList)" prop="title" label="标题" show-overflow-tooltip></el-table-column>
			<el-table-column v-if="$tools.isShow('sort', tableShowList)" prop="sort" label="排序" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column label="操作" fixed="right" min-width="180">
				<template slot-scope="scope">
					<!-- <el-button
						v-if="$tools.hasPermission('study:exam:studyQuestion:info')"
						size="mini"
						plain
						@click="handleInfo(scope.row.id)"
					>
						详情
					</el-button> -->
					<!--					<el-button v-if="$tools.hasPermission('study:exam:studyQuestion:edit')" size="mini" plain @click="handleEditSort(scope.row)">-->
					<!--						调整顺序-->
					<!--					</el-button>-->
					<el-button v-if="$tools.hasPermission('study:exam:studyQuestion:edit')" size="mini" plain @click="handleEdit(scope.row.id)">
						编辑
					</el-button>
					<el-button v-if="$tools.hasPermission('study:exam:studyQuestion:delete')" size="mini" plain type="danger" @click="handleDelete(scope.row)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination :total="page.total" :current-page="page.current" :page-size="page.size" @refreshData="queryList"></pagination>
		<!-- 新增、编辑 -->
		<form-edit v-if="formEditVisible" ref="formEdit" @refreshData="queryList"></form-edit>
		<!-- 详情 -->
		<form-info v-if="formInfoVisible" ref="formInfo"></form-info>
		<!-- 题目导入弹窗 -->
		<el-dialog @close="close" title="导入信息" :visible.sync="importVisible" width="50%" center>
			<!-- <div style="padding: inherit; text-align: center">
				您可以先
				<a href="https://resource-1251334741.cos.ap-beijing.myqcloud.com/exam_study/%E9%A2%98%E5%BA%93%E6%A8%A1%E6%9D%BF.xls"><span style="color: #cf9236">下载模板</span></a>
				，按照下载的表格信息后，开始导入
			</div>
			<el-form :model="importForm" :rules="importDataRule" ref="importForm">
				<el-form-item prop="url" style="text-align: center">
					<fortress-upload type="file" :multiple="false" name="url" :formData="importForm" @upload-success="successHandle" :isShowTip="false"></fortress-upload>
					<div class="el-upload__tip">只能上传xls/xlsx文件</div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="questionsImport" :loading="loadingStatus">开始导入</el-button>
			</span> -->
			<!-- <div class="tip">
				为了确保数据的准确，请按照以下规则进行导入
				<a href="https://doc.icuapi.com/" target="doc">了解更多</a>
			</div>
			<div class="body">
				<div class="title">
					<span class="number">1</span>
					下载表单模板
				</div>
				<div class="content">
					<div class="item">· 按照规范示例.xlsx在模板内录入数据;</div>
					<div class="item">· 只导入第一张工作表(sheet1);</div>
					<div class="item">· 请勿修改表格标题，防止导入失败。</div>
				</div>
				<el-button class="el-button" @click="toDownloadTemplate">下载表单模板</el-button>
			</div>
			<div class="body">
				<div class="title">
					<span class="number">2</span>
					上传文件
				</div>
				<div class="content">
					<div class="item">· 请上传*.xls，.xlsx格式文件;</div>
					<div class="item">· 当前版本最多只允许上传5000条数据且文件大小不超过1M;</div>
				</div>

				<div class="file">
					<fortress-upload type="file" :multiple="false" name="url" :formData="importForm" @upload-success="successHandle" :isShowTip="false"></fortress-upload>
				</div>
			</div>

			<template #footer>
				<div class="footer">
					<el-button type="primary" @click="questionsImport" :loading="loadingStatus">开始导入</el-button>
					<el-button class="cancel-btn" type="info" :loading="loadingStatus" @click="cancel">取消</el-button>
				</div>
			</template> -->
		</el-dialog>
	</div>
</template>
<script>
import { studyquestionPage, studyquestionDel, studyquestionDelBatch, studyquestionDynamicExport, studyquestionDynamicImport } from "@/api/study/exam/studyquestion.js"
import { viewTableList } from "@/api/public.api.js"
import FormEdit from "./studyquestion-edit"
import FormInfo from "./studyquestion-info"
import FortressPagination from "@/components/fortress-pagination.vue"
import { urlList } from "@/api/public.api.js"
import request from "@/common/request"

export default {
	data() {
		return {
			tableData: [],
			formEditVisible: false,
			formInfoVisible: false,
			queryForm: {
				qbId: "",
				questionType: "",
				title: "",
			},
			page: {
				current: 1,
				size: 10,
				total: 0,
			},
			collapse: {
				icon: "el-icon-arrow-down el-icon--right",
				label: "展开",
				flag: false,
			},
			tableList: [],
			tableShowList: [],
			qbIdList: [],
			questionTypeList: [],
			importVisible: false,
			loadingStatus: false,
			importForm: {
				url: "",
				qbId: this.$route.query.id,
			},
			fileList: [],
			uploadUrl: window.$conf.commonConf.baseUrl + "/system/oss/upload",
		}
	},
	components: {
		"form-edit": FormEdit,
		"form-info": FormInfo,
		pagination: FortressPagination,
	},
	created() {
		this.queryForm.qbId = this.$route.query.qbId || ""
		this.queryUrlList()
		this.queryJsonList()
		this.initTableList()
		this.queryList()
	},
	methods: {
		async onUpload(file) {
			console.log(file.file)
			try {
				let formdata = new FormData()
				formdata.append("upfile", file.file)
				const res = await request("post", this.uploadUrl, formdata)
				if (res.code == 0) {
					this.$refs.import.loading = false
					// this.$refs.import.cancel()
					try {
						this.getImportFile(res.data.url)
						this.$refs.import.cancel()
					} catch (error) {
						this.$refs.import.cancel()
					}
				} else {
					this.$refs.import.loading = false
				}
			} catch (error) {
				this.$refs.import.loading = false
				this.$refs.import.cancel()
			}
		},
		toDownloadTemplate() {
			window.open("https://resource-1251334741.cos.ap-beijing.myqcloud.com/exam_study/%E9%A2%98%E5%BA%93%E6%A8%A1%E6%9D%BF.xls")
		},
		//批量导入题目
		addBatchHandle() {
			this.importVisible = true
			this.importForm.qbId = this.$route.query.id
		},
		// 关闭
		close() {
			this.fileList = []
			this.importForm = {
				url: "",
			}
		},
		// 判断上传数量
		handleExceed() {
			this.$message.warning("一次最多导入一个文件")
		},
		// 上传之前
		beforeUploadHandle(file) {
			if (file.type !== "application/vnd.ms-excel" && file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
				this.$message.error("只能上传xls/xlsx文件")
				return false
			}
		},
		// 上传成功
		async successHandle(res) {
			if (res[0].code !== 0) {
				return this.$message.error(res[0].msg)
			}
			this.importForm.url = res[0].data
			// this.$nextTick(() => {
			// 	this.$refs["importForm"].validate()
			// })
		},
		// 导入
		questionsImport() {
			this.loadingStatus = true
			this.getImportFile()
		},
		getImportFile(url) {
			studyquestionDynamicImport({
				url: url,
				qbId: this.$route.query.qbId,
			})
				.then(res => {
					// this.loadingStatus = false
					if (res.code !== 0) {
						// this.loadingStatus = false
						return this.$message.error(res.msg)
					}
					this.$message({
						message: "导入成功",
						type: "success",
						duration: 500,
					})
					// this.loadingStatus = false
					// this.importVisible = false
					this.queryList()
				})
				.catch(err => {
					// this.loadingStatus = false
					console.log(err, "err")
				})
		},
		cancel() {
			this.$refs["importForm"].resetFields()
			this.importVisible = false
		},
		queryUrlList() {
			this.qbIdList = []
			urlList("/study/exam/studyQuestionbank/list").then(resp => {
				if (resp.code == 0) {
					if (resp.data) {
						resp.data.forEach(item => {
							this.qbIdList.push({ code: item.id, name: item.qbName })
						})
					}
				}
			})
		},
		queryJsonList() {
			this.questionTypeList = []
			let questionTypeListData = '[{"code":"单选题","name":"单选题"},{"code":"多选题","name":"多选题"}]'
			this.questionTypeList = JSON.parse(questionTypeListData)
		},
		refresh() {
			this.tableData = []
			this.queryList({ current: 1 })
		},
		//查询表格数据
		queryList(page) {
			if (page) {
				this.page.current = page.current ? page.current : this.page.current
				this.page.size = page.size ? page.size : this.page.size
			}
			this.queryForm.current = this.page.current
			this.queryForm.size = this.page.size
			studyquestionPage(this.queryForm).then(resp => {
				if (resp.code == 0) {
					this.tableData = resp.data.records
					this.page.total = resp.data.total
					//查询页大于总页数，重新查询
					let cu = this.page.total % this.page.size == 0 ? parseInt(this.page.total / this.page.size) : parseInt(this.page.total / this.page.size + 1)
					if (cu > 0 && this.page.current > cu) {
						this.queryList({ current: cu })
					}
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		//打开编辑窗口
		handleEdit(id) {
			this.formEditVisible = true
			this.$nextTick(() => {
				this.$refs.formEdit.init(id, this.queryForm.qbId)
			})
		},
		//打开详情窗口
		handleInfo(id) {
			this.formInfoVisible = true
			this.$nextTick(() => {
				this.$refs.formInfo.init(id)
			})
		},
		//删除
		handleDelete(row) {
			this.$confirm("确认删除该记录, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					studyquestionDel(row.id).then(resp => {
						if (resp.code == 0) {
							this.$message({
								type: "success",
								message: "操作成功!",
							})
							//判断是否最后一页的最后一条记录
							let totalPages = (this.page.total - 1) % this.page.size == 0 ? (this.page.total - 1) / this.page.size : (this.page.total - 1) / this.page.size + 1
							if (this.page.current > totalPages && this.page.current != 1) {
								this.page.current = this.page.current - 1
							}
							this.queryList()
						} else {
							this.$msg({
								message: resp.msg,
								type: "error",
							})
						}
					})
				})
				.catch(() => {})
		},
		//批量删除
		handleDeleteBatch() {
			let checkedRow = this.$refs.multipleTable.selection
			if (checkedRow.length > 0) {
				let ids = []
				checkedRow.forEach(item => {
					ids.push(item.id)
				})
				this.$confirm("确认删除该记录, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						studyquestionDelBatch(ids).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								//判断是否最后一页的最后一条记录
								let totalPages = (this.page.total - checkedRow.length) % this.page.size == 0 ? (this.page.total - checkedRow.length) / this.page.size : (this.page.total - checkedRow.length) / this.page.size + 1
								if (this.page.current > totalPages && this.page.current != 1) {
									this.page.current = this.page.current - 1
								}
								this.queryList()
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
					})
					.catch(() => {})
			} else {
				this.$msg({
					message: "请选择数据进行删除",
					type: "error",
				})
			}
		},
		//重置查询框
		resetQueryForm() {
			this.queryForm = {
				questionType: "",
				title: "",
				qbId: this.$route.query.qbId || "",
			}
			this.queryList({ current: 1 })
		},
		//切换查询条件收缩框
		handleCollapseState() {
			this.collapse.flag = !this.collapse.flag
			if (this.collapse.flag) {
				this.collapse.icon = "el-icon-arrow-up el-icon--right"
				this.collapse.label = "收起"
			} else {
				this.collapse.icon = "el-icon-arrow-down el-icon--right"
				this.collapse.label = "展开"
			}
		},
		//视图表格列表初始化
		initTableList() {
			viewTableList("study_question").then(resp => {
				if (resp.code == 0) {
					this.tableList = resp.data
					this.tableList.forEach(item => {
						this.tableShowList.push(item.propName)
					})
				}
			})
		},
		//题目类型格式化返回
		questionTypeFmt(row) {
			let name = ""
			if (this.questionTypeList) {
				this.questionTypeList.forEach(item => {
					if (item.code == row.questionType) {
						name = item.name
					}
				})
			}
			return name
		},
		//可见字段excel导出
		handleExport() {
			if (!this.tableShowList || this.tableShowList.length < 1) {
				this.$msg({
					message: "请选择要导出的列",
					type: "error",
				})
				return
			}
			let colNum = 1
			let headerList = []
			this.tableShowList.forEach(item => {
				let nameData = this.tableList.find(item2 => {
					return item2.propName == item
				})
				let name = ""
				if (nameData && nameData.propDesc) {
					name = nameData.propDesc
				} else {
					name = "未定义字段" + colNum++
				}
				headerList.push({ name: name, code: item })
			})
			studyquestionDynamicExport({ headerList: headerList, dto: this.queryForm })
		},
		handleEditSort(row) {
			row.editSortFlag = true
		},
	},
	computed: {
		importDataRule() {
			return {
				url: [
					{
						required: true,
						message: "请上传xls文件",
						trigger: "blur",
					},
				],
			}
		},
	},
}
</script>
<style scoped lang="scss">
.tip {
	background: #f4f5f5;
	color: #90959b;
	box-sizing: border-box;
	padding-left: 20px;
	padding-right: 20px;
	padding-top: 7px;
	padding-bottom: 7px;
	a {
		color: #0d6efd;
		&:hover {
			text-decoration: underline;
		}
	}
}
.body {
	padding: 0 30px;
	box-sizing: border-box;
	.title {
		line-height: 50px;
		font-size: 16px;
		font-weight: 700;
		span {
			font-weight: 500;
			display: inline-block;
			width: 18px;
			height: 18px;
			border-radius: 50%;
			color: #fff;
			background: #0d6efd;
			text-align: center;
			line-height: 18px;
			font-size: 14px;
		}
	}
	.content {
		background: #f4f5f5;
		color: #8d9299;
		box-sizing: border-box;
		padding: 10px 15px;
		margin-bottom: 15px;
		line-height: 1.8;
	}
	.file {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.el-button {
		display: block;
		margin: auto;
		width: 170px;
		position: relative;
		.upload {
			position: absolute;
			z-index: 5;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			opacity: 0;
			cursor: pointer;
		}
	}
}
.footer {
	// padding-top: 30px;
	display: flex;
	justify-content: center;
	align-items: center;
	.cancel-btn {
		background: #f0f0f0;
		border: 1px solid #f0f0f0;
		color: #666;
	}
}
</style>
